package com.dlwx.firefighting;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.dlwx.firefighting.activity.BaseActivity;
import com.dlwx.firefighting.activity.PayCodeActivity;
import com.dlwx.firefighting.activity.UserQrCodeActivity;
import com.dlwx.firefighting.bean.UserBean;
import com.dlwx.firefighting.config.Constant;
import com.dlwx.firefighting.fragment.CartFragment;
import com.dlwx.firefighting.fragment.IndexFragment;
import com.dlwx.firefighting.fragment.MyFragment;
import com.dlwx.firefighting.fragment.StoreFragment;
import com.dlwx.firefighting.fragment.order.UserOrderFragment;
import com.dlwx.firefighting.utils.LogUtils;
import com.dlwx.firefighting.utils.SPUtils;
import com.dlwx.firefighting.utils.ToastUtils;
import com.fm.openinstall.OpenInstall;
import com.fm.openinstall.listener.AppWakeUpListener;
import com.fm.openinstall.model.AppData;
import com.fm.openinstall.model.Error;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends BaseActivity implements AppWakeUpListener {
    @BindView(R.id.fragmentRoot)
    FrameLayout fragmentRoot;
    @BindView(R.id.ll_zero)
    LinearLayout llZero;
    @BindView(R.id.ll_one)
    LinearLayout llOne;
    @BindView(R.id.ll_two)
    LinearLayout llTwo;
    @BindView(R.id.ll_three)
    LinearLayout llThree;
    @BindView(R.id.bottom_nav_container)
    LinearLayout bottomNavContainer;
    private ArrayList<View> bottomNavs;
    private FragmentManager manager;
    private FragmentTransaction transaction;
    private IndexFragment indexFragment;
    private StoreFragment storeFragment;
    private CartFragment cartFragment;
    private MyFragment myFragment;
    private UserOrderFragment orderFragment;
    private String userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        userId = (String) SPUtils.get(MainActivity.this, Constant.USER_ID, "");
        manager = getSupportFragmentManager();

        initView();
        OpenInstall.getWakeUp(getIntent(), this);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        getDatas();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //此处要调用，否则App在后台运行时，会无法截获
        OpenInstall.getWakeUp(intent, this);
    }


    private void initView() {
        //initFragment();
        bottomNavs = new ArrayList<>();
        for (int i = 0; i < bottomNavContainer.getChildCount(); i++) {
            View child = bottomNavContainer.getChildAt(i);
            child.setTag(i);
            bottomNavs.add(child);
//            child.setOnClickListener(this);
        }
        bottomNavs.get(0).setSelected(true);
        startFragment(0);
    }

    private void getDatas() {
        OkGo.<String>post(Constant.USER)
                .tag(this)
                .params("user_id", userId)
                .params("action", "user_info")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        DealResult dealResult = new DealResult();
//                        List<UserBean> beans = dealResult.deal(MainActivity.this, response, new TypeToken<BaseBean<UserBean>>() {
//                        }.getType());
//                        setDatas(beans);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        ToastUtils.toastForShort(MainActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    private void setDatas(List<UserBean> beans) {
        if (beans.isEmpty()) {
            return;
        }
        SPUtils.put(MainActivity.this, Constant.IS_PAY, beans.get(0).is_pay());
    }


//    @Override
//    public void onClick(View v) {
//        //先重置
//        reset();
//        v.setSelected(true);
//        int i = (int) v.getTag();
//        transaction = manager.beginTransaction();
//        startFragment(i);
//    }

    private void reset() {
        for (View v : bottomNavs) {
            v.setSelected(false);
        }
    }

    private void startFragment(int i) {
        transaction = manager.beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        reset();
        bottomNavs.get(i).setSelected(true);
        switch (i) {
            case 0:
                if (indexFragment != null) {
                    transaction.show(indexFragment);
                } else {
                    indexFragment = new IndexFragment();
                    transaction.add(R.id.fragmentRoot, indexFragment, "homeFragment");
                }
                break;
            case 2:
                if (orderFragment != null) {
                    transaction.show(orderFragment);
                } else {
                    orderFragment = new UserOrderFragment();
                    transaction.add(R.id.fragmentRoot, orderFragment, "orderFragment");
                }
                break;
            case 1:
                if (cartFragment != null) {
                    transaction.show(cartFragment);
                } else {
                    cartFragment = new CartFragment();
                    transaction.add(R.id.fragmentRoot, cartFragment, "shoppingCartFragment");
                }
                break;
            case 3:
                if (myFragment != null) {
                    transaction.show(myFragment);
                } else {
                    myFragment = new MyFragment();
                    transaction.add(R.id.fragmentRoot, myFragment, "meFragment");
                }
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    long exitTime = 0;

    // 点击返回按钮
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtils.toastForShort(MainActivity.this, "再按一次退出程序");
                exitTime = System.currentTimeMillis();
                return false;
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 隐藏fragment
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (indexFragment != null) {
            transaction.hide(indexFragment);
        }
        if (orderFragment != null) {
            transaction.hide(orderFragment);
        }
        if (cartFragment != null) {
            transaction.hide(cartFragment);
        }
        if (myFragment != null) {
            transaction.hide(myFragment);
        }
    }

    @Override
    public void onWakeUpFinish(AppData appData, Error error) {
        if (error == null) {
            Log.d("OpenInstall", "getWakeUp : wakeupData = " + appData.toString());
        } else {
            Log.d("OpenInstall", "getWakeUp : errorMsg = " + error.toString());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
//        payee_id=1&payee_name=anan&payee_phone=
        if (result != null) {
            String content = result.getContents();
            LogUtils.d(content);
            Intent i = new Intent(MainActivity.this, PayCodeActivity.class);
            if (content != null && content.contains("cashier")) {
//                向收银员支付
                i.putExtra("content", result.getContents());
                i.putExtra("type", "0");
                startActivity(i);
            } else if (content != null && content.contains("payee")) {
//           向会员支付
                boolean b = (boolean) SPUtils.get(MainActivity.this, Constant.IS_SCAN, false);
                if (b) {
                    i.putExtra("content", result.getContents());
                    i.putExtra("type", "1");
                    startActivity(i);
                } else {
                    ToastUtils.toastForShort(MainActivity.this, "请先申请会员支付权限");
                    startActivity(new Intent(MainActivity.this, UserQrCodeActivity.class));
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @OnClick({R.id.ll_zero, R.id.ll_one, R.id.ll_two, R.id.ll_three})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_zero:
                startFragment(0);
                break;
            case R.id.ll_one:
                startFragment(1);
                break;
            case R.id.ll_two:
                startFragment(2);
                break;
            case R.id.ll_three:
                startFragment(3);
                break;
        }
    }
}
